
// pages/pay/pay.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    total:0,
    goodsList:[
      // {
      //   id:1,
      //   name:"小米手机",
      //   img:"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/d9d7f31258a1f84a277918cecab14aaa.jpg?f=webp&w=516&h=420",
      //   price:"2999",
      //   priceOld:"3999",
      //   num:1,
      //   checked:false
      // },
      // {
      //   id:2,
      //   name:"小米手机2",
      //   img:"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/d9d7f31258a1f84a277918cecab14aaa.jpg?f=webp&w=516&h=420",
      //   price:"2999",
      //   priceOld:"3999",
      //   num:1,
      //   checked:false
      // },
    ],
    showAddress:false,  //选择地址按钮
    indexAddress:1,  //确认地址下标
    name:"",  //地址姓名
    tel:"",  //电话
    city:"",  //地址城市
    detail:"", //详细地址
    code:"",  //邮政编码
    addressList:[],  //地址数组
    showEdit:false,  //显示编辑按钮
    editId:null,  //编辑地址id
    addressOnly:[]  //单条地址

  },
  // 计算总价格
  totalData(){
    let num = 0;
    let data = this.data.goodsList.reduce((total,item)=>{
      if(item.checked){
        num++;
        return total += item.price * item.num;
      }else{
        return total
      }
    },0)
    this.setData({
      total:data,
    })
  },
  // 跳转地址列表 新增地址
  setIndex(){
    if(!this.data.showAddress){
      this.setData({
        showAddress:true
      })
    }else if(this.data.showAddress && this.data.indexAddress == 1){
      this.setData({
        indexAddress:0
      })
    }else if(this.data.showAddress && this.data.indexAddress == 0 ){
      this.setData({
        indexAddress:1
      })
    }
  },
  //确定选择
  shutdown(){

    this.setData({
      showAddress:false
    })
  },
  // 姓名输入框
  bindInputName(e){
    // console.log(e.target);
    // console.log(e.detail);
    this.setData({
      name:e.detail.value
    })

    // console.log(this.data.name);
    
  },
  // 电话输入框
  bindInputTel(e){
    this.setData({
      tel:e.detail.value
    })

    // console.log(this.data.tel);
  },
  // 地址输入框
  bindInputCity(e){
    this.setData({
      city:e.detail.value
    })

    // console.log(this.data.city);
  },
  // 详细地址输入框
  bindInputDetail(e){
    this.setData({
      detail:e.detail.value
    })

    // console.log(this.data.detail);
  },
  // 邮政编码输入框
  bindInputCode(e){
    this.setData({
      code:e.detail.value
    })

    // console.log(this.data.code);
  },
  // 新增地址
  addMy(){
    // 新增地址到地址数组里面
    this.data.addressList.push({
      id:new Date().getTime(),
      name:this.data.name, 
      tel:this.data.tel,  
      city:this.data.city, 
      detail:this.data.detail,
      code:this.data.code,
      checked:false 
    })

    // console.log(this.data.addressList);
    if(this.data.name == "" || this.data.tel == "" || this.data.city == "" || this.data.detail == ""){
      // 保存成功提示
      wx.showToast({
        title: '请添加数据',
        icon: 'error',
      });
    }else if(this.data.name != "" && this.data.tel != "" && this.data.city != "" && this.data.detail != ""){
      // 保存成功提示
      wx.showToast({
       title: '添加成功',
       icon: 'success',
     });
      // 添加地址到数据存储
      wx.setStorageSync('addressList', this.data.addressList);

      // 清空输入框
    this.setData({
      addressList:this.data.addressList,
      name:"",  //地址姓名
      tel:"",  //电话
      city:"",  //地址城市
      detail:"", //详细地址
      code:"",  //邮政编码
    })

    }
   
    
   
  },
  // 删除地址
  delAddress(e){
    let addressList = this.data.addressList.filter(item => item.id != e.target.dataset.id);
    // 更新页面数据
    this.setData({
      addressList:addressList
    })
    wx.setStorageSync('addressList', addressList);
  },

  // 编辑地址
  editAddress(e){
    this.setData({
      showEdit:true
    })
    let id = e.target.dataset.id;
    let index = this.data.addressList.findIndex(item => item.id == id)
    // 同步到修改地址栏
    this.setData({
      name:this.data.addressList[index].name, 
      tel:this.data.addressList[index].tel,  
      city:this.data.addressList[index].city, 
      detail:this.data.addressList[index].detail,
      code:this.data.addressList[index].code,
      editId:e.target.dataset.id
    })
    
  },
  // 保存编辑地址
  editSet(e){
    let id = this.data.editId;
    let index = this.data.addressList.findIndex(item => item.id == id)
    // 修改地址
    this.setData({
      ["addressList["+index+"].name"]:this.data.name, 
      ["addressList["+index+"].tel"]:this.data.tel,  
      ["addressList["+index+"].city"]:this.data.city, 
      ["addressList["+index+"].detail"]:this.data.detail,
      ["addressList["+index+"].code"]:this.data.code,
      editId:null
    });

    // console.log(this.data.addressList);
    // 保存成功提示
    wx.showToast({
      title: '修改成功',
      icon: 'success',
    });

     // 添加地址到数据存储
     wx.setStorageSync('addressList', this.data.addressList);

     // 清空输入框
    this.setData({
      showEdit:false,  //关闭编辑框
      name:"",  //地址姓名
      tel:"",  //电话
      city:"",  //地址城市
      detail:"", //详细地址
      code:"",  //邮政编码
    })

  },
  // 选择地址列表
  checkChange(e){
    let id = e.target.dataset.id;
    let index = this.data.addressList.findIndex(item => item.id == id);
    
    for(let i = 0 ; i<this.data.addressList.length;i++){

      if(i == index){
        if(this.data.addressList[index].checked){
          this.data.addressList[index].checked = false;
        }else if(!this.data.addressList[index].checked){
          this.data.addressList[index].checked = true;
        }

        // console.log( this.data.addressList[i].checked)
        // console.log(index);
      }else{
        this.data.addressList[i].checked = false;
        // console.log( this.data.addressList[i].checked,"111")
      }
    }
    // 同步数据
    this.setData({
      addressList:this.data.addressList
    })
    // 添加地址到数据存储
    wx.setStorageSync('addressList', this.data.addressList);
  },
  // 确认地址
  checkAddress(){
    
    this.setData({
      addressOnly:this.data.addressList.filter(item => item.checked == true),
      showAddress:false
    });
    // console.log(addressOnly)
  },
  // 跳转订单页
  goOrder(){
    //隐藏加载界面
    // wx.hideLoading();

    wx.showModal({
      title: '支付商品',
      success:(res)=>{
        if (res.confirm) {
          // console.log('用户点击确定')
          this.setOrderList(2);//生成订单--待发货
        } else if (res.cancel) {
          // console.log('用户点击取消')
          this.setOrderList(1);//生成订单--待支付
        }


        // 定时器
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/order/order',
          })

          // 支付之后删除立即购买
          wx.removeStorageSync('payLists');
         }, 1000);

       //显示加载界面
       wx.showLoading({  // 显示加载中loading效果 
        title: "加载中",
        mask: true,  //开启蒙版遮罩
        duration: 2000 
      });
       
      }
    })
    


  },

  // 生成订单
  // 1.待支付 2.待发货 3.待收货 4.待评价
  setOrderList(type){
      
      // 构造订单数据
      let orderData = {
        orderId: new Date().getTime(),
        orderLists:this.data.goodsList,//商品列表
        type:type,
        total:this.data.total,//总价格
        // address:{
        //     name:"张三",
        //     phone:"13012341234",
        //     address:"广东省广州市天河区XXX路XXX号"
        // }
        address:this.data.addressOnly[0]
      };

      // 1.判断缓存有没有数据
      let goodsOrderList = wx.getStorageSync('goodsOrderList');
      if(goodsOrderList){
        // 2.有数据 添加数据
        goodsOrderList.push(orderData);
        wx.setStorageSync('goodsOrderList', goodsOrderList)

      }else{
        // 3.没有数据 添加订单
        wx.setStorageSync('goodsOrderList', [orderData])
      }


      // 删除订单数据
      let goodsCarList = wx.getStorageSync('goodsCarList');
      let newlists = goodsCarList.filter(item=>!item.checked); //过滤加入订单数据
      wx.setStorageSync('goodsCarList', newlists)

  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 获取缓存数据
    let goodsCarList = wx.getStorageSync('goodsCarList');
    // let dataLists = goodsCarList.filter(item=>item.checked);

    // 判断是否有立即购买
    if(wx.getStorageSync('payLists')){
      this.data.goodsList = wx.getStorageSync('payLists');
      // console.log(dataLists,"111");
    }else{
      this.data.goodsList = goodsCarList.filter(item=>item.checked);
    }

    // 判断是否有地址数组
    if(wx.getStorageSync('addressList')){
      this.data.addressList = wx.getStorageSync('addressList');
      
      this.setData({
        // 剪切数组
        addressOnly:this.data.addressList.slice(0,1)
      })
      // console.log(this.data.addressOnly)
    }
    

    this.setData({
      // goodsList:dataLists
      goodsList:this.data.goodsList,
      addressList:this.data.addressList
    })

    this.totalData();//计算总价格

    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

    // 删除立即购买本地缓存
    wx.removeStorageSync('payLists');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})